package com.liwang.lanouhn.nvshengo.fragments;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.liwang.lanouhn.nvshengo.Info.MsgEvent;
import com.liwang.lanouhn.nvshengo.R;
import com.liwang.lanouhn.nvshengo.activities.SelfInformationActivity;
import com.liwang.lanouhn.nvshengo.activities.SetActivity;
import com.squareup.picasso.Picasso;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by lanouhn on 2016/9/29.
 */
public class SelfFragment extends Fragment {
    private CircleImageView iv_head;
    private TextView tv_login, tv_attention2, tv_subscibe2;
    private TextView tv_introduce, tv_data;
    private ImageView iv_edit, iv_set;
    private TextView tv_attention;
    private RelativeLayout rl_attention;
    private TextView tv_subscibe;
    private RelativeLayout rl_subscibe;
    private FrameLayout login_framlayout;
    private FragmentManager fm = getFragmentManager();
    private AttentionFragment attention;
    private SubscibeFragment subscibe;
    private Tencent mTencent;
    private QQAuth mQQAuth;
    //判断是否登录
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    //记录账号信息
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor personEditor;

    private boolean isLogin = false;

    private UserInfo mInfo;
    private IUiListener userInfoListener;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, null);

        return view;
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        sp = getActivity().getSharedPreferences("login", getActivity().MODE_PRIVATE);
        editor = sp.edit();
        sharedPreferences = getActivity().getSharedPreferences("person", getActivity().MODE_PRIVATE);
        personEditor = sharedPreferences.edit();
        mQQAuth = QQAuth.createInstance("1105697617", getActivity().getApplicationContext());
        mTencent = Tencent.createInstance("1105697617", getActivity().getApplicationContext());
        initView(getView());
        initData();
        personImage();
        initEvent();
    }
    private void initView(View view) {
        iv_head = (CircleImageView) view.findViewById(R.id.iv_head);
        tv_login = (TextView) view.findViewById(R.id.tv_login);
        tv_data = (TextView) view.findViewById(R.id.tv_data);
        tv_introduce = (TextView) view.findViewById(R.id.tv_introduce);
        iv_edit = (ImageView) view.findViewById(R.id.iv_edit);
        iv_set = (ImageView) view.findViewById(R.id.iv_set);
        tv_attention = (TextView) view.findViewById(R.id.tv_attention);
        rl_attention = (RelativeLayout) view.findViewById(R.id.rl_attention);
        tv_subscibe = (TextView) view.findViewById(R.id.tv_subscibe);
        rl_subscibe = (RelativeLayout) view.findViewById(R.id.rl_subscibe);
        login_framlayout = (FrameLayout) view.findViewById(R.id.login_framlayout);
        tv_attention2 = (TextView) view.findViewById(R.id.tv_attention2);
        tv_subscibe2 = (TextView) view.findViewById(R.id.tv_subscibe2);
        String text = getActivity().getIntent().getStringExtra("text");
        if (null != text) {
            tv_introduce.setText(text);
        }

    }

    private void initData() {
        isLogin = sp.getBoolean("isLogin", false);
        if (!isLogin) {
            iv_head.setImageResource(R.mipmap.unlogin);
            tv_login.setText("点击头像登录");
            tv_data.setText("登录查看更多精彩呦 !");
        } else {
            tv_login.setText(sharedPreferences.getString("name", "旺"));
            tv_data.setText(sharedPreferences.getString("content", "824546067"));
            Picasso.with(getActivity()).load(sharedPreferences.getString("icon", "")).into(iv_head);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);//注册
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(MsgEvent event){
       tv_introduce.setText(event.text);
    }



    private void personImage() {
        //获取用户信息
        userInfoListener = new IUiListener() {
            @Override
            public void onError(UiError arg0) {
            }

            @Override
            public void onComplete(Object arg0) {

                if (arg0 == null) {
                    return;
                }
                try {
                    JSONObject jo = (JSONObject) arg0;
                    int ret = jo.getInt("ret");
                    System.out.println("json=" + String.valueOf(jo));
                    String nickName = jo.getString("nickname");
                    String gender = jo.getString("gender");
                    String figureurl_qq_2 = jo.getString("figureurl_qq_2");
                    tv_login.setText(nickName);
                    tv_data.setText("欢迎来到美丽go世界 ！");
                    Picasso.with(getActivity()).load(figureurl_qq_2).into(iv_head);

                    editor.putBoolean("isLogin", true);
                    editor.commit();

                    personEditor.putString("name", nickName);
                    personEditor.putString("content", "欢迎来到美丽Higo !");
                    personEditor.putString("icon", figureurl_qq_2);
                    personEditor.commit();
                } catch (Exception e) {
                }
            }

            @Override
            public void onCancel() {

            }
        };
    }
    private void initEvent() {
        attention = new AttentionFragment();
        subscibe = new SubscibeFragment();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.add(R.id.login_framlayout, attention);
        transaction.add(R.id.login_framlayout, subscibe);
        transaction.hide(subscibe);
        transaction.commit();

        rl_attention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_attention.setTextColor(getResources().getColor(R.color.black));
                tv_attention2.setTextColor(getResources().getColor(R.color.black));
                tv_subscibe.setTextColor(getResources().getColor(R.color.grays));
                tv_subscibe2.setTextColor(getResources().getColor(R.color.grays));
                FragmentTransaction left_transaction = getFragmentManager().beginTransaction();
                left_transaction.hide(subscibe);
                left_transaction.show(attention);
                left_transaction.commit();
            }
        });
        rl_subscibe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_subscibe.setTextColor(getResources().getColor(R.color.black));
                tv_subscibe2.setTextColor(getResources().getColor(R.color.black));
                tv_attention.setTextColor(getResources().getColor(R.color.grays));
                tv_attention2.setTextColor(getResources().getColor(R.color.grays));
                FragmentTransaction left_transaction = getFragmentManager().beginTransaction();
                left_transaction.hide(attention);
                left_transaction.show(subscibe);
                left_transaction.commit();
            }
        });
        iv_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin) {
                    Intent intent = new Intent(getActivity(), SetActivity.class);
                    startActivity(intent);
                } else {
                    login();
                }
            }
        });
        iv_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent2 = new Intent(getActivity(), SelfInformationActivity.class);
                startActivity(intent2);
            }
        });

    }

    //获取token值
    class BaseUiListener implements IUiListener {
        protected void doComplete(Object values) {

        }

        @Override
        public void onComplete(Object value) {
            doComplete(value);
            if (value == null) {
                return;
            }

            try {
                JSONObject jo = (JSONObject) value;
                int ret = jo.getInt("ret");
                if (ret == 0) {
                    String openID = jo.getString("openid");
                    String accessToken = jo.getString("access_token");
                    String expires = jo.getString("expires_in");
                    mTencent.setOpenId(openID);
                    mTencent.setAccessToken(accessToken, expires);
                    Log.i("aaa", "values=" + value);

                    mInfo = new UserInfo(getActivity(), mQQAuth, mTencent.getQQToken());
                    mInfo.getUserInfo(userInfoListener);
                }

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {

        }

        @Override
        public void onCancel() {

        }
    }


    //注销
    public void logout() {
        mTencent.logout(getActivity());
        tv_login.setText("点击头像登录");
        tv_data.setText("登录查看更多精彩呦 !");
        iv_head.setImageResource(R.mipmap.unlogin);
    }


    //登录
    public void login() {
        if (!mTencent.isSessionValid()) {
            mTencent.login(this, "all", new BaseUiListener());
        }
    }


    //信息回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mTencent.onActivityResultData(requestCode, resultCode, data, new BaseUiListener());
    }


}
